package fwk.impl;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.coyote.Adapter;

import fwk.Controller;
import fwk.HandlerAdapter;
import fwk.HandlerMapping;

public class DispatcherServlet extends HttpServlet{
	private BeanFactory bf=null;
	@Override
	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		//读配置文件，并产生相就反射动作
		//开始读配置文件，并生成BeanFactory
		//获取配置文件位置
		String configInfo=config.getInitParameter("config");
		String filePath=this.getServletContext().getRealPath("/WEB-INF/")+"/"+configInfo;
		//实例化BeanFactory
		bf=new BeanFactory(filePath);
		System.out.println("初始化完成.......");
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		doPost(req, resp);
	}
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		
		//完成前端控制器中所有的动作
		//1、请求映射
		HandlerMapping mapping=(HandlerMapping)bf.getBean(BeanFactory.HANDLER_MAPPING_NAME);
		//2、获取请求路径
		String uri=preUri(req.getRequestURI());
		//3、获取Controller
		System.out.println(uri);
		Controller controller=mapping.mapController(uri);
		System.out.println(controller);
		//4、用HanderAdapter处理Controller
		HandlerAdapter adpater=(HandlerAdapter)bf.getBean(BeanFactory.HANDLER_ADAPTER_NAME);
		ModelAndView mv=adpater.processController(controller,req,resp);
	
	}
	private String preUri(String s){
		int start=s.indexOf("/", 1);
		String rs=s.substring(start);
		return rs;
	}
	
	
	public static void main(String[] args) {
		
	}
	
	
	
	
}
